<template>
  <div style="width: 100%">
    <el-form
      :model="formData"
      label-width="100px"
      ref="userform"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              :disabled="type === 'edit'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名字" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex">
              <el-option
                v-for="item in sexList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="mail">
            <el-input v-model="formData.mail"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门" prop="orgPid">
            <!-- <el-input v-model="formData.orgPid"></el-input> -->
            <treeselect
              :check-strictly="true"
              :normalizer="normalizer"
              :options="options"
              :props="{ label: 'nameCn', id: 'pid' }"
              v-model="formData.orgPid"
            >
              <div slot="value-label" slot-scope="{ node }">
                {{ node.raw && node.raw.nameCn }}
              </div>
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="secretData.length > 0">
          <el-form-item label="密级" prop="classification">
            <el-select v-model="formData.classification">
              <el-option
                v-for="(item, idx) in secretData"
                :key="idx"
                :disabled="item.disabled"
                :label="`${item.nameCn}(${item.name})`"
                :value="item.pid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像" prop="avatar">
            <el-upload
              v-model="formData.avatar"
              :key="formData.avatar"
              class="avatar-uploader"
              action="/file-api/mx-file/uploadpicture"
              accept="image/jpg,image/jpeg,image/png"
              :http-request="uploadFile"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formData.avatar"
                :src="formData.avatar"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="rolePid">
            <!-- <el-input v-model="formData.rolePid"></el-input> -->
            <el-select v-model="formData.rolePid" multiple>
              <el-option
                v-for="(item, idx) in roleOptions"
                :key="idx"
                :disabled="item.disabled"
                :label="item.nameCn"
                :value="item.pid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户分组">
            <!-- <el-switch v-model="formData.lockFlag"> </el-switch> -->
            <el-select v-model="formData.userGroupPid" multiple>
              <el-option
                v-for="(item, idx) in userGroupOptions"
                :key="idx"
                :disabled="item.disabled"
                :label="`${item.nameCn}(${item.name})`"
                :value="item.pid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="position">
            <!-- <el-input v-model="formData.rolePid"></el-input> -->
            <el-select v-model="formData.position">
              <el-option
                v-for="item in positionData"
                :key="item.value"
                :label="item.name"
                :value="Number(item.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="签名" prop="signature">
            <el-upload
              v-model="formData.signature"
              :key="formData.signature"
              class="avatar-uploader"
              action="/file-api/mx-file/uploadpicture"
              accept="image/jpg,image/jpeg,image/png"
              :http-request="uploadSignFile"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formData.signature"
                :src="formData.signature"
                class="sign"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用">
            <!-- <el-switch v-model="formData.lockFlag"> </el-switch> -->
            <el-radio-group v-model="formData.lockFlag">
              <el-radio :label="0">有效</el-radio>
              <el-radio :label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="md-component-btns">
      <el-button size="medium" type="primary" @click="save">保存</el-button>
      <el-button size="medoptionsium" @click="$emit('removeThisTabs')"
        >取消</el-button
      >
    </div>
  </div>
</template>

<script>
import * as api from "@/api/userManage/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as common from "@/api/common";

export default {
  name: "userManageTemp",
  components: { Treeselect },
  props: {
    type: String,
    data: Object,
  },
  data() {
    return {
      options: [],
      roleOptions: [],
      secretData: [],
      positionData: [],
      userGroupOptions: [],
      formData: {
        username: "",
        password: "",
        name: "",
        phone: "",
        orgPid: "",
        rolePid: "",
        classification: "",
        lockFlag: 0,
        signature: "",
        avatar: "",
      },
      sexList: [
        {
          label: "男",
          value: 0,
        },
        {
          label: "女",
          value: 1,
        },
      ],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        /*password: [{ required: true, message: "请输入密码", trigger: "blur" }],*/
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        // lastName: [
        //   { required: true, message: "请输入末名字", trigger: "blur" },
        // ],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        orgPid: [{ required: true, message: "请输入部门", trigger: "blur" }],
        // rolePid: [{ required: true, message: "请输入角色", trigger: "blur" }],
      },
    };
  },
  mounted() {},
  methods: {
    uploadSignFile(file) {
      // 创建 FormData 对象
      const formData = new FormData();
      // 将文件添加到 FormData 中
      formData.append("file", file.file);
      // 发起上传文件的请求
      common
        .uploadImg(formData)
        .then((response) => {
          // 文件上传成功的处理逻辑
          this.$message.success("上传成功！");
          this.formData.signature = response.data.data;
        })
        .catch((error) => {
          // 文件上传失败的处理逻辑
          this.$message.error("上传失败！");
        });
    },
    uploadFile(file) {
      // 创建 FormData 对象
      const formData = new FormData();
      // 将文件添加到 FormData 中
      formData.append("file", file.file);
      // 发起上传文件的请求
      common
        .uploadImg(formData)
        .then((response) => {
          // 文件上传成功的处理逻辑
          this.$message.success("上传成功！");
          this.formData.avatar = response.data.data;
        })
        .catch((error) => {
          // 文件上传失败的处理逻辑
          this.$message.error("上传失败！");
        });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    getSecret() {
      // common.getDic("secret").then((res) => {
      //   this.secretData = res.data.data;
      // });
      common.getDic("position").then((res) => {
        this.positionData = res.data.data;
      });
    },
    getFilterData(data) {
      const newData = data.map((v) => {
        if (v.children && v.children.length === 0) {
          const noChild = { ...v };
          delete noChild.children;
          return {
            ...noChild,
          };
        }
        return {
          ...v,
          children: this.getFilterData(v.children),
        };
      });
      return newData;
    },
    normalizer(node) {
      return {
        id: node.pid,
        label: node.nameCn,
        children: node.children,
      };
    },
    getUserTree() {
      api.getUserTree().then((res) => {
        let data = res.data.data;
        if (data && data.length > 0) {
          this.options = this.getFilterData(data);
        }
      });
    },
    getRoleList() {
      let applicationId = localStorage.getItem("appId");
      api.getRoleList().then((res) => {
        let data = res.data.data;
        this.roleOptions = data.map(v=>({...v,disabled: v.applicationId !== applicationId}));
      });
    },
    getUserGroupList() {
      const applicationId = localStorage.getItem("appId");
      api.getUserGroupList().then((res) => {
        let data = res.data.data;
        // this.userGroupOptions = data.filter((v) => v.isSecurity !== 1);
        this.userGroupOptions = data.map(v=>{
          if(v.isSecurity !== 1){
            return {
              ...v,
              disabled: v.applicationId !== applicationId
            }
          }
          
        }).filter(v=>!!v);
        // this.secretData = data.filter((v) => v.isSecurity === 1);
        this.secretData = data.map(v=>{
          if(v.isSecurity === 1){
            return {
              ...v,
              disabled: v.applicationId !== applicationId
            }
          }
          
        }).filter(v=>!!v);
      });
    },
    save() {
      this.$refs.userform.validate((f) => {
        if (f) {
          let applicationId = localStorage.getItem("appId");
          const params = {
            ...this.formData,
            applicationId,
            rolePid: this.formData.rolePid
              ? this.formData.rolePid.join(",")
              : "",
          };
          const email = /(^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$)/;
          if (params.mail && !email.test(params.mail)) {
            this.$message.error("邮箱格式错误");
            return;
          }
          const phone = /^1[3-9]\d{9}$/;
          if (params.phone && !phone.test(params.phone)) {
            this.$message.error("手机号格式错误");
            return;
          }
          if (
            this.formData.userGroupPid &&
            this.formData.userGroupPid.length > 0
          ) {
            params.userGroupPid = this.formData.userGroupPid.join(",");
          } else {
            params.userGroupPid = "";
          }
          if (this.type === "edit") {
            params.pid = this.data.pid;
            delete params.password;
            delete params.applicationName;
            api.updateUser(params).then(() => {
              this.$message.success("编辑成功");
              this.$emit("refresh");
              this.$emit("removeThisTabs");
            });
          } else {
            api.addUser(params).then(() => {
              this.$message.success("保存成功");
              this.$emit("refresh");
              this.$emit("removeThisTabs");
            });
          }
        }
      });
    },
    getDetails(pid) {
      api.detail({ id: pid }).then((res) => {
        const newData = res.data.data;
        this.formData = {
          ...this.formData,
          ...newData,
          classification: newData.classification
            ? newData.classification.toString()
            : "",
          rolePid: newData.rolePid ? newData.rolePid.split(",") : [],
        };
        if (newData.userGroupPid) {
          this.formData.userGroupPid = newData.userGroupPid.split(",");
        }
      });
    },
    getOptionsAndTree() {
      this.getUserTree();
      this.getRoleList();
      this.getUserGroupList();
      this.getSecret();
    },
    open(row) {
      this.getOptionsAndTree();
      this.formData = {
        ...this.formData,
        ...row,
      };
    },
    view(row) {
      this.getOptionsAndTree();
      this.getDetails(row.pid);
    },
    edit(row) {
      this.getOptionsAndTree();
      this.getDetails(row.pid);
    },
  },
};
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
}
.sign {
  width: 580px;
  height: 320px;
}
</style>
